<template>
  <div class="container mx-auto min-h-screen">
    <HomeHeader @change-tabs="handleChangeTabs" @search="handleSearch" :activeTab="activeTab" :scrollProgress="scrollProgress" />
    <div class="px-4">
      <div v-if="activeTab !== 2">
        <div v-for="item in properties" :key="item.id">
          <div class="text-lg mb-3 mt-4 inline-block mr-2" @click="handleGoList(item)">{{ isZh ? item.name : item.nameEn }}</div>
          <van-icon name="arrow" @click="handleGoList(item)" />
          <ScrollGrid :items="item.spuList" @updateFavorite="handleUpdateFavorite" />
        </div>
      </div>
      <div v-if="activeTab !== 2">
        <div v-for="item in properties" :key="item.id">
          <div class="text-lg mb-3 mt-4 inline-block mr-2" @click="handleGoList(item)">{{ isZh ? item.name : item.nameEn }}</div>
          <van-icon name="arrow" @click="handleGoList(item)" />
          <ScrollGrid :items="item.spuList" @updateFavorite="handleUpdateFavorite" />
        </div>
      </div>
      <div v-if="activeTab !== 2">
        <div v-for="item in properties" :key="item.id">
          <div class="text-lg mb-3 mt-4 inline-block mr-2" @click="handleGoList(item)">{{ isZh ? item.name : item.nameEn }}</div>
          <van-icon name="arrow" @click="handleGoList(item)" />
          <ScrollGrid :items="item.spuList" @updateFavorite="handleUpdateFavorite" />
        </div>
      </div>
      <div v-if="activeTab !== 2">
        <div v-for="item in properties" :key="item.id">
          <div class="text-lg mb-3 mt-4 inline-block mr-2" @click="handleGoList(item)">{{ isZh ? item.name : item.nameEn }}</div>
          <van-icon name="arrow" @click="handleGoList(item)" />
          <ScrollGrid :items="item.spuList" @updateFavorite="handleUpdateFavorite" />
        </div>
      </div>
      <div v-if="activeTab === 2" class="promotional-features py-6 bg-white mt-3 rounded-lg">
        <div v-for="feature in promotionalFeatures" :key="feature.id" class="flex mb-6 px-3">
          <div class="w-6 h-6 bg-gradient-to-br from-orange-400 to-orange-500 rounded-full mr-4 shadow-lg"></div>
          <div class="flex-1 text-gray-800 text-base font-medium leading-relaxed">{{ $t(`home.features.${feature.key}`) }}</div>
        </div>
      </div>
    </div>

    <!-- 提示弹框组件 -->
    <TipDialog :visible.sync="tipDialogVisible" :type="tipDialogType" @button-click="handleTipAction" @close="handleTipClose" />

    <div class="p-4 bg-gray-100 mt-10 text-[14px]">
      <div class="text-[15px] font-bold">{{ $t("foot.about") }}</div>
      <div class="">
        {{ isZh ? configFootInfo.about && configFootInfo.about.content : configFootInfo.aboutEn && configFootInfo.aboutEn.content }}
      </div>
      <div class="text-[15px] font-bold mt-2 mb-1">{{ $t("foot.contact") }}</div>
      <div class="flex items-center">
        <img :src="imageBaseUrl + (configFootInfo.concatEmail && configFootInfo.concatEmail.icon)" class="w-4 h-4 mr-2" alt="" />
        <span>{{ configFootInfo.concatEmail && configFootInfo.concatEmail.content }}</span>
      </div>
      <div class="flex items-center" v-if="configFootInfo.concatPhone && configFootInfo.concatPhone.content">
        <img :src="imageBaseUrl + configFootInfo.concatPhone && configFootInfo.concatPhone.icon" class="w-4 h-4 mr-2" alt="" />
        <span>{{ configFootInfo.concatPhone && configFootInfo.concatPhone.content }}</span>
      </div>
      <!-- 关注我们 -->
      <div class="text-[15px] font-bold mt-2 mb-1">{{ $t("foot.follow") }}</div>
      <div class="flex items-center">
        <img
          :src="imageBaseUrl + item.icon"
          class="w-6 h-6 mr-2"
          v-for="(item, index) in configFootInfo.followList"
          :key="index"
          @click="handleFollow(item)" />
      </div>
      <!-- 付款方式 -->
      <div class="text-[15px] font-bold mt-2 mb-1">{{ $t("foot.payment") }}</div>
      <div class="flex items-center">
        <img :src="imageBaseUrl + item.icon" class="w-6 h-6 mr-2" v-for="(item, index) in configFootInfo.payList" :key="index" />
      </div>
      <!-- 页脚协议 -->
      <div class="text-[14px] mt-2 mb-1 text-[#ff7a00]">
        <span v-for="(item, index) in configFootInfo.articleList" :key="index" @click="handleArticle(item)" class="cursor-pointer">
          {{ isZh ? item.title : item.titleEn }}
          <span v-if="index < configFootInfo.articleList.length - 1" class="mx-2">|</span>
        </span>
      </div>

      <div class="w-full text-center">
        <div>{{ configFootInfo.year }}yoyotravel 版权所有</div>
        <div>202403095356 (CA0383295-W)</div>
      </div>
    </div>
    <div class="h-[50px]" :class="{ 'translate-y-full': !showTabbar }"></div>
    <van-tabbar route :class="['z-999 transition-transform duration-300', { 'translate-y-full': !showTabbar }]">
      <van-tabbar-item :to="item.to" v-for="item in tabbarItems" :key="item.name">
        <template #icon>
          <img :src="item.icon" :class="{ 'w-10 h-10': item.w === 10, 'w-8 h-8': item.w === 8 }" />
        </template>
      </van-tabbar-item>
    </van-tabbar>
  </div>
</template>

<script>
import HomeHeader from "@/components/home/HomeHeader.vue"
import PropertyGrid from "@/components/home/PropertyGrid.vue"
import ScrollGrid from "@/components/home/ScrollGrid.vue"
import TipDialog from "@/components/home/TipDialog.vue"
import { Locale, Tabbar, TabbarItem } from "vant"
// 引入英文语言包
import enUS from "vant/es/locale/lang/en-US"
import zhCN from "vant/es/locale/lang/zh-CN"
import { mapActions, mapGetters, mapMutations } from "vuex"
import { getCategoryList } from "@/apis/shop"
import { getConfigFootList } from "@/apis/common"

export default {
  name: "Home",
  components: {
    HomeHeader,
    PropertyGrid,
    ScrollGrid,
    TipDialog,
    [Tabbar.name]: Tabbar,
    [TabbarItem.name]: TabbarItem,
  },
  data() {
    return {
      properties: [],
      promotionalFeatures: [
        { id: 1, key: "register", icon: "user-circle-o" },
        { id: 2, key: "discount", icon: "gold-coin-o" },
        { id: 3, key: "packages", icon: "globe" },
        { id: 4, key: "esimFree", icon: "send-gift-o" },
        { id: 5, key: "simple", icon: "like-o" },
        { id: 6, key: "gifts", icon: "gift-o" },
      ],
      activeTab: 0,
      // 提示弹框相关
      tipDialogVisible: false,
      tipDialogType: "language", // 'language', 'password', 'review'

      active: 1,
      tabbarItems: [
        { name: "cart", icon: require("@/assets/images/card.png"), to: { name: "cart", query: { showTabbar: true } }, w: 8 },
        { name: "home", icon: require("@/assets/images/home.png"), to: { name: "home" }, w: 8 },
        { name: "yoyoCoinIntroduce", icon: require("@/assets/images/yoyo.png"), to: { name: "yoyoCoinIntroduce" }, w: 10 },
        { name: "mine", icon: require("@/assets/images/mine.png"), to: { name: "mine" }, w: 10 },
      ],

      // 滚动相关状态
      showTabbar: true,
      lastScrollTop: 0,
      scrollThreshold: 15, // tabbar滚动阈值
      configFootInfo: {},
      // 防抖相关
      tabbarScrollTimer: null,
      // HomeHeader 相关
      scrollProgress: 0, // 0-1 之间的滚动进度，用于HomeHeader动画
      maxScrollForHeaderAnimation: 80, // HomeHeader动画完成的最大滚动距离
    }
  },
  methods: {
    ...mapMutations({
      setLoginDialogVisible: "auth/SET_LOGIN_DIALOG_VISIBLE",
      setIsZh: "lang/SET_IS_ZH",
    }),
    ...mapActions({
      fetchUserInfo: "auth/fetchUserInfo",
    }),
    handleFollow(item) {
      if (item.content) {
        window.open(item.content)
      }
    },
    handleArticle(item) {
      this.$router.push({ name: "article", query: { id: item.id } })
    },
    async getCategoryList() {
      try {
        console.log("this.activeTab :>> ", this.activeTab)
        const type = this.activeTab === 1 ? "sim" : "esim"
        const res = await getCategoryList({ type })
        this.properties = res.data
        console.log("categoryList :>> ", res)
      } catch (error) {}
    },
    // 处理滚动事件 - 分离的简洁逻辑
    handleScroll() {
      const scrollTop = window.pageYOffset || document.documentElement.scrollTop
      const windowHeight = window.innerHeight
      const documentHeight = document.documentElement.scrollHeight

      // 1. 立即更新 HomeHeader 的滚动进度（无防抖，实时响应）
      this.updateHeaderScrollProgress(scrollTop)

      // 2. 防抖处理 Tabbar 逻辑
      if (this.tabbarScrollTimer) {
        clearTimeout(this.tabbarScrollTimer)
      }

      this.tabbarScrollTimer = setTimeout(() => {
        this.updateTabbarVisibility(scrollTop, windowHeight, documentHeight)
      }, 100) // 100ms 防抖
    },

    // HomeHeader 滚动进度更新（实时、线性）
    updateHeaderScrollProgress(scrollTop) {
      // 简单的线性计算：0-80px 范围内从 0 到 1
      this.scrollProgress = Math.min(scrollTop / this.maxScrollForHeaderAnimation, 1)
    },

    // Tabbar 显示逻辑（防抖、方向判断）
    updateTabbarVisibility(scrollTop, windowHeight, documentHeight) {
      // 判断是否滚动到页面底部
      const isNearBottom = scrollTop + windowHeight >= documentHeight - 50

      // 页面底部总是显示 tabbar
      if (isNearBottom) {
        this.showTabbar = true
        this.lastScrollTop = scrollTop
        return
      }

      // 计算滚动方向和距离
      const scrollDiff = scrollTop - this.lastScrollTop
      const scrollDirection = scrollDiff > 0 ? "down" : "up"

      // 只有滚动距离超过阈值才切换状态
      if (Math.abs(scrollDiff) > this.scrollThreshold) {
        if (scrollDirection === "down" && scrollTop > 80) {
          // 向下滚动且超过80px，隐藏tabbar
          this.showTabbar = false
        } else if (scrollDirection === "up") {
          // 向上滚动，显示tabbar
          this.showTabbar = true
        }
        
        // 更新最后滚动位置
        this.lastScrollTop = scrollTop
      }
    },

    handleGoList(item) {
      this.$router.push({ name: "productsList", query: { id: item.id } })
    },
    handleSearch() {
      if (!this.isLoggedIn) {
        this.setLoginDialogVisible(true)
      } else {
        this.$router.push("/query")
      }
    },
    handleChangeTabs(index) {
      this.activeTab = index
      this.getCategoryList()
    },
    // 显示不同类型的提示弹框
    showLanguageDialog() {
      this.tipDialogType = "language"
      this.tipDialogVisible = true
    },
    showPasswordDialog() {
      this.tipDialogType = "password"
      this.tipDialogVisible = true
    },
    showReviewDialog() {
      this.tipDialogType = "review"
      this.tipDialogVisible = true
    },

    // 处理提示弹框按钮点击
    handleTipAction({ action }) {
      console.log(`提示弹框操作 - 类型: ${this.tipDialogType}, 操作: ${action}`)

      // 根据不同类型和操作处理逻辑
      if (this.tipDialogType === "language") {
        // 切换语言，持久化到 localStorage
        const newLang = action === "english" ? "en" : "zh-CN"
        this.$i18n.locale = newLang
        Locale.use(newLang === "en" ? "en-US" : "zh-CN", newLang === "en" ? enUS : zhCN)
        localStorage.setItem("lang", newLang)
        this.setIsZh(newLang === "zh-CN")
        // 触发界面重新渲染，以确保文本切换生效
        this.$forceUpdate()
        this.handleTipClose()
      } else if (this.tipDialogType === "password") {
        if (action === "setPassword") {
          console.log("跳转到密码设置页面")
          // 可以在这里跳转到密码设置页面
          this.$router.push("/user-info")
        } else if (action === "later") {
          this.handleTipClose()
        }
      } else if (this.tipDialogType === "review") {
        if (action === "review") {
          console.log("跳转到评价页面")
          // 可以在这里跳转到评价页面
        } else if (action === "dismiss") {
          this.handleTipClose()
        }
      }
    },

    // 处理提示弹框关闭
    handleTipClose() {
      console.log(`提示弹框关闭 - 类型: ${this.tipDialogType}`)
      this.tipDialogVisible = false
    },
    handleUpdateFavorite(id, favorite) {
      this.getCategoryList()
    },
    async getConfigFootList() {
      try {
        const res = await getConfigFootList()
        this.configFootInfo = res.data
        console.log("configFootInfo :>> ", res)
      } catch (error) {
        console.log("error :>> ", error)
      }
    },
  },
  computed: {
    ...mapGetters({
      isLoggedIn: "auth/isLoggedIn",
      userInfo: "auth/userInfo",
      isZh: "lang/isZh",
    }),
    imageBaseUrl() {
      return process.env.VUE_APP_IMAGE_URL
    },
  },

  created() {
    // 添加滚动事件监听
    window.addEventListener("scroll", this.handleScroll, { passive: true })
    // this.fetchUserInfo().then(() => {
    //   console.log("用户信息获取成功", this.userInfo)
    //   if (!this.userInfo.hasPassword) {
    //     this.showPasswordDialog()
    //   }
    //   if (this.userInfo.hasUnCommentOrder) {
    //     this.showReviewDialog()
    //   }
    // }).catch((error) => {
    //   console.error("用户信息获取失败", error)
    // })
    if (!localStorage.getItem("lang")) {
      this.showLanguageDialog()
    }
    this.getCategoryList()
    this.getConfigFootList()
  },
  watch: {
    userInfo: {
      handler(newVal) {
        console.log("home---userInfo :>> ", newVal)
        if (newVal) {
          if (!newVal.hasPassword) {
            this.showPasswordDialog()
          }
          if (newVal.hasUnCommentOrder) {
            this.showReviewDialog()
          }
        }
      },
      deep: true,
      immediate: false,
    },
    isLoggedIn: {
      handler(newVal) {
        console.log("home---isLoggedIn :>> ", newVal)
      },
      deep: true,
      immediate: false,
    },
  },
  beforeDestroy() {
    // 移除滚动事件监听
    window.removeEventListener("scroll", this.handleScroll)
    // 清理定时器
    if (this.tabbarScrollTimer) {
      clearTimeout(this.tabbarScrollTimer)
    }
  },
}
</script>

<style scoped>
/deep/.van-tabbar-item__icon img {
  height: auto;
}
</style>
